package com.swn.common.util;

import org.apache.log4j.Logger;

import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.dubbo.rpc.RpcResult;

/**
 * dubbo白名单过滤器
 * 
 * @author taozhaocai
 * @Date 2017年9月4日  下午3:42:51
 * @Note 需要配置：在resources目录下添加纯文本文件META-INF/dubbo/com.alibaba.dubbo.rpc.Filter  
 */
public class AuthorityFilter implements Filter {  
	private static Logger logger = Logger.getLogger("AuthorityFilter.class");
    
	private String whiteIp="";  //服务器启动时，自动读取过来。多个ip用特殊符号连接
  
  
    @Override  
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {  
    	String clientIp = RpcContext.getContext().getRemoteHost(); 
    	/*System.out.println(RpcContext.getContext().getRemoteAddressString());
    	System.out.println(RpcContext.getContext().getUrl());
    	System.out.println(RpcContext.getContext().getRemoteHostName());*/
//    	System.out.println("clientIp:"+clientIp);
     
    	//whiteIp为空，则视为所有ip都可以访问
    	if(whiteIp==null||"".equals(whiteIp)){
       	 return invoker.invoke(invocation);
       }
  
        
        //白名单允许访问
        if(whiteIp.contains(clientIp)){
        	 return invoker.invoke(invocation);
        }else{
        	 logger.error("禁止访问的ip为{}"+clientIp);  
        	 return new RpcResult();
        }

    }  
}  
